var mqtt = require("../../utils/mqtt.min.js")

const options = {
  connectTimeout: 3000,
  clientId: function () {
    return Math.random().toString(36).substr(2, 15)
  },
};
const deviceConfig = {
  deviceName: "hardware",
};

var client;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    mqValue:{
      temperature: 0,
      humidity: 0,
      soilHum: 0,
    },

  },  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    let that = this;
    //创建websocket,需要域名、ssl证书
    client = mqtt.connect('wxs://www.baidu.com/mqtt',options)
    client.on('connect', function () {
      console.log('连接服务器成功')
      client.subscribe('v1/devices/telemetry', function (err) {
        if (!err) {
           console.log('订阅成功！');
        }
      })
    })
	//接收消息监听
    client.on('message', function (topic, message) {
      // message is Buffer
      let msg = message.toString();
      console.log('收到消息：'+msg);
      //解析json数据
      let temp  =JSON.parse(msg);
      that.setData({
        mqValue: temp
      });
     //关闭连接 client.end()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' &&
    this.getTabBar()) {
    this.getTabBar().setData({
      selected: 0
    })
  }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onWaterChange: function(event) {
    var that = this
    console.log(event.detail)
    let sw = event.detail.value
    // 要发布的主题
    let topicdown = `v1/devices/me/rpc/${deviceConfig.deviceName}`
    let wateroff = `{"params":{"WaterOutletSwitch":0},"version":"1.0.0"}`
    let wateron  = `{"params":{"WaterOutletSwitch":1},"version":"1.0.0"}`
    if (sw) {
      client.publish(topicdown, wateron, function (err) {
        if (!err) {
          console.log('成功下发命令 开始浇水!')
        }
      })
    } else {
      client.publish(topicdown, wateroff, function (err) {
        if (!err) {
          console.log('成功下发命令 停止浇水!')
        }
      })
    }
  },


})